#!/usr/bin/perl

##
## Copyright (C) 2011 Luciano Xumerle <luciano.xumerle@gmail.com>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

use strict;
use warnings;

my $VERSION = 'Version 0.1 (08 Sep 2011)';

my @dir = ();

my $onlyTOP = 0;
my $onlyDEF = 0;

foreach (@ARGV)
{
    if (m/-h/) { &printSet(1); exit; }
    if (m/-t/) { $onlyTOP++; }
    if (m/-d/) { $onlyDEF++; }
    elsif ( -d $_ && -f $_ . '/settings.txt' && -f $_ . '/reads.1.fastq' )
    {
        push @dir, $_;
    }
}

if ( defined $dir[0] && -d $dir[0] )
{
    print STDERR qq|PARAMETERS
directory: @dir
|;
}
else
{
    &printSet();
    exit;
}

foreach my $dir (@dir)
{
    $dir =~ s/\/+$//;
    my $set = $dir . '/settings.txt';
    chdir $dir;
    my %pars = ();

    open( FILE, $set ) || die;
    while (<FILE>)
    {
        chomp;
        next if ( m/^\s*$/ || m/^#/ );
        my @a = split /\t/;
        $pars{ $a[0] } = $a[1];
    }
    close FILE;

    if ( $onlyDEF == 0 )
    {

        ### TOPHAT
        if ( !-f $dir . '/accepted_hits.bam' )
        {
            my @gogo = (
                $pars{TOPHAT},                       '--rg-id',
                $pars{RGID},                         '--rg-sample',
                $pars{NAME},                         '--rg-desc',
                $pars{NAME},                         '--rg-center',
                $pars{LAB},                          '--rg-platform-unit',
                $pars{PLATFORM} . '_' . $pars{DATE}, '--rg-platform',
                $pars{PLATFORM},                     '--rg-date',
                $pars{DATE},                         '-o',
                $dir,                                '-G',
                $pars{DEFUSEDB} . '/' . $pars{GTF}
            );
            push @gogo, ( '-r', $pars{INNER}, '--mate-std-dev', $pars{INNERSD} )
              if ( -f $dir . 'reads.2.fastq' );
            push @gogo,
              (
                '-p', $pars{CPU}, $pars{DEFUSEDB} . '/' . $pars{BOWTIEDB},
                'reads.1.fastq'
              );
            push @gogo, 'reads.2.fastq' if ( -f $dir . 'reads.2.fastq' );
            system(@gogo);
        }

        ### CUFFLINKS
        if ( !-f $dir . '/transcripts.gtf' )
        {
            system( $pars{CUFFLINKS},
                '-u',
                '-G',
                $pars{DEFUSEDB} . '/' . $pars{GTF},
                '-b',
                $pars{DEFUSEDB} . '/' . $pars{FASTA},
                '--no-update-check',
                '--verbose',
                '-p',
                $pars{CPU},
                '-o',
                $dir,
                $dir . '/accepted_hits.bam'
            );
        }

        ### VARSCAN SNPS
        if ( !-f $dir . '/accepted_hits.pileup2snp' )
        {
`$pars{SAMTOOLS} mpileup -f $pars{DEFUSEDB}/$pars{FASTA} $dir/accepted_hits.bam | java -Xmx2g -jar $pars{VARSCAN} pileup2snp --p-value 0.9 > $dir/accepted_hits.pileup2snp`;
        }

        ### VARSCAN INDELS
        if ( !-f $dir . '/accepted_hits.pileup2indel' )
        {
`$pars{SAMTOOLS} mpileup -f $pars{DEFUSEDB}/$pars{FASTA} $dir/accepted_hits.bam | java -Xmx2g -jar $pars{VARSCAN} pileup2indel --p-value 0.9 > $dir/accepted_hits.pileup2indel`;
        }
    }    # if onlydef

    ### DEFUSE
    if ( $onlyTOP == 0 )
    {
        system( $pars{DEFUSEHOME} . '/scripts/defuse.pl', '-c',
            $pars{DEFUSEDB} . '/config.txt', '-d',
            $dir,                            '-o',
            $dir . '/defuse',                '-p',
            $pars{CPU}
        );

        rename(
            $dir . '/defuse/results.classify.tsv',
            $dir . '/results.classify.tsv'
        );
        rename(
            $dir . '/defuse/results.filtered.tsv',
            $dir . '/results.filtered.tsv'
        );
        rename( $dir . '/defuse/results.tsv', $dir . '/results.tsv' );
        system( '/bin/rm', '-fr', $dir . '/defuse' );
    }
}    # foreach cartelle

sub printSet
{
    my $pp = shift;
    my $nn = $0;
    $nn =~ s/^.\///;
    print qq|Copyright (C) 2011 Luciano Xumerle
$VERSION

SYNTAX:
$nn [-t] [-d] <directory1> <directory2> ...

<directory> must contains files reads.1.fastq and reads.2.fastq

-d : execute only defuse pipeline
-t : execute only tophat/cufflinks/varscan pipeline
-h : print <settings.txt> example to STDOUT
|;

    if ( defined $pp && $pp == 1 )
    {
        print q|======================================================
Each assay folder contains 3 files:
reads.1.fastq
reads.2.fastq
settings.txt

The sequence ID in reads.?.fastq must have
the suffix '/1' ('/2' in the second pair).

vvv SETTINGS EXAMPLE vvv
CPU	3
TOPHAT	/usr/local/bin/tophat
CUFFLINKS	/usr/local/bin/cufflinks
SAMTOOLS	/usr/local/bin/samtools
VARSCAN	/home/ciano/Scaricati/VarScan.v2.2.7.jar

DEFUSEHOME	/proj/genome/prog/defuse-0.4.1/
DEFUSEDB	/proj/genome/prog/defuse-0.4.1/hg19/

GTF	Homo_sapiens.GRCh37.62.gtf
BOWTIEDB	Homo_sapiens.GRCh37.62.dna.chromosome.fa
FASTA	Homo_sapiens.GRCh37.62.dna.chromosome.fa.fa


PLATFORM	Illumina
RGID	controllo
NAME	test
LAB	CGF_Verona_HiSeq1000
DATE	2009-06-05
INNER	110
INNERSD	100
^^^ SETTINGS EXAMPLE ^^^
(The separator in settings.txt is the TAB character)
|;
    }
}

sub convertFastq
{
    my $file = shift;
    open( FILE, $file )
      || die("Serve un nome file con le reads. Rimuovo la coda dell'id.\n\n");
    while (<FILE>)
    {
        if (m/^\@HWI/) { s/\s+([12]).+/\/$1/; }
        print;
    }
    close FILE;
}

